<?php

/**
 * 功能描述：锁定
 * Created by PhpStorm.
 * User: dennis
 * Date: 2017/6/10
 * Time: 17:22
 */
namespace app\cls\tom;
class Lock {
    private $redis;
    private $lockPrefix;
    const _MAX_LOCK_TIME = 600;

    public function __construct($name, $redis = null) {
        if (!empty($redis)) {
            $this->redis = $redis;
        } else {
            $this->redis = SysResource::getRedis();
        }
        $this->lockPrefix = "__tom_lock_{$name}_";
    }

    /**
     * 功能描述：设置redis
     * @param $redis
     */
    public function setRedis($redis) {
        $this->redis = $redis;
    }

    /**
     * 功能描述：释放锁定
     * @param $identify
     * @return int
     */
    public function unLock($identify) {
        return $this->redis->del($this->lockPrefix.$identify);
    }

    /**
     * 更新锁定的时间
     * @param $identify
     * @param $expire
     */
    public function updateLockExpire($identify,$expire) {
        $expire = intval($expire);
        $this->redis->expire($this->key.$identify, $expire);
    }

    /**
     * 功能描述：尝试去获取锁，不会阻塞
     * @param $identify
     * @param $expire
     * @return bool
     */
    public function tryLock($identify,$expire = 0) {
        $expire = intval($expire);
        if (empty($expire)) {
            $expire = self::_MAX_LOCK_TIME;
        }
        $num = $this->redis->incr($this->lockPrefix.$identify);
        if ($num == 1) {
            $this->redis->expire($this->lockPrefix.$identify, $expire);
            return true;
        } else {
            return false;
        }
    }
}